package com.songlanyun.modules.applyareaagent.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.SysConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.entity.UserVerifiedEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserVerifiedService;
import com.songlanyun.modules.applyareaagent.entity.*;
import com.songlanyun.modules.shop.entity.ShopAdminRelationEntity;
import com.songlanyun.modules.shop.model.vo.ShopSlimVO;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.user.entity.SysUserEntity;
import com.songlanyun.modules.user.service.SysRoleService;
import com.songlanyun.modules.user.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.applyareaagent.dao.ApplyAreaAgentDao;
import com.songlanyun.modules.applyareaagent.service.ApplyAreaAgentService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("applyAreaAgentService")
public class ApplyAreaAgentServiceImpl extends ServiceImpl<ApplyAreaAgentDao, ApplyAreaAgentEntity> implements ApplyAreaAgentService {

    @Autowired
    private AccountService accountService;

    @Resource
    private SysRoleService sysRoleService;


    @Autowired
    private UserVerifiedService userVerifiedService;

    @Autowired
    private ShopService shopService;

    @Resource
    private SysUserService sysUserService;


    @Override
    public ApplyAreaAgentEntity create(ApplyAreaAgentEntity entity) {
        this.baseMapper.insert(entity);
        return entity;
    }

    @Override
    public ApplyAreaAgentEntity modify(ApplyAreaAgentEntity entity) {
        this.baseMapper.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Long id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String provinceCode = MapUtil.getStr(params, "province_code");
        String cityCode = MapUtil.getStr(params, "city_code");
        String areaCode = MapUtil.getStr(params, "area_code");
        Integer status = MapUtil.getInt(params, "status");
        String mobile = MapUtil.getStr(params, "mobile");
        String nickname = MapUtil.getStr(params, "nickname");
        Integer lock = MapUtil.getInt(params, "lock");

        IPage<ApplyAreaAgentEntity> page = this.page(
                new Query<ApplyAreaAgentEntity>().getPage(params),
                new LambdaQueryWrapper<ApplyAreaAgentEntity>()
                        .eq(StringUtils.isNotBlank(provinceCode), ApplyAreaAgentEntity::getProvinceCode, provinceCode)
                        .eq(StringUtils.isNotBlank(cityCode), ApplyAreaAgentEntity::getCityCode, cityCode)
                        .eq(StringUtils.isNotBlank(areaCode), ApplyAreaAgentEntity::getAreaCode, areaCode)
                        .eq(ObjectUtil.isNotNull(status) && status > -1, ApplyAreaAgentEntity::getStatus, status)
                        .eq(ObjectUtil.isNotNull(lock) && lock == 1, ApplyAreaAgentEntity::getStatus, 1)
        );

        return new PageUtils(page);
    }


    @Override
    public void apply(Long userId, ApplyAreaAgentDTO dto) {
        accountService.getUserById(userId, true);
        UserVerifiedEntity optionUserVerifiedEntity = userVerifiedService.loadById(userId, false);
        if (ObjectUtil.isNull(optionUserVerifiedEntity)) {
            throw new RRException("您还没有实名不能申请区域代理");
        }

        ApplyAreaAgentEntity entity = this.loadBy(dto.getProvinceCode(), dto.getCityCode(), dto.getAreaCode());
        if (ObjectUtil.isNotNull(entity)) {
            throw new RRException("有人已经申请，不能复重申请");
        }

        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<ApplyAreaAgentEntity>()
                .eq(ApplyAreaAgentEntity::getProvinceCode, dto.getProvinceCode())
                .eq(ApplyAreaAgentEntity::getCityCode, dto.getCityCode())
                .eq(ApplyAreaAgentEntity::getAreaCode, dto.getAreaCode())
                .eq(ApplyAreaAgentEntity::getUserId, userId));
        if (count > 0) {
            throw new RRException("申请过的地区就不要再申请");
        }

        ApplyAreaAgentEntity obj = new ApplyAreaAgentEntity();

        BeanUtil.copyPropertiesIgnoreNull(dto, obj);
        obj.setUserId(userId);
        obj.setApplyTime(new Date());
        obj.setStatus(0);
        this.create(obj);
    }

    @Override
    public ApplyAreaAgentEntity loadBy(String provinceCode, String cityCode, String areaCode) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<ApplyAreaAgentEntity>()
                .eq(ApplyAreaAgentEntity::getProvinceCode, provinceCode)
                .eq(ApplyAreaAgentEntity::getCityCode, cityCode)
                .eq(ApplyAreaAgentEntity::getAreaCode, areaCode)
                .eq(ApplyAreaAgentEntity::getStatus, 1)
                .last("limit 1"));
    }

    @Override
    public ApplyAreaAgentEntity loadByUserId(Long userId) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<ApplyAreaAgentEntity>()
                .eq(ApplyAreaAgentEntity::getUserId, userId)
                .last("limit 1"));
    }

    @Override
    public ApplyAreaAgentEntity check(ApplyAreaAgentCheckDTO dto) {
        ApplyAreaAgentEntity entity = this.loadById(dto.getId(), true);
        String provinceCode = entity.getProvinceCode();
        String cityCode = entity.getCityCode();
        String areaCode = entity.getAreaCode();
        if(dto.getStatus()==1) {
            ApplyAreaAgentEntity entity2 = loadBy(provinceCode, cityCode, areaCode);
            if (ObjectUtil.isNotNull(entity2)) {
                throw new RRException("该地区已存在区域经营商");
            }
        }
        entity.setStatus(dto.getStatus());
        entity.setCheckInfo(dto.getCheckInfo());
        this.modify(entity);
        return entity;
    }

    @Override
    public ApplyAreaAgentEntity loadById(Long id, boolean b) {
        ApplyAreaAgentEntity obj = this.getById(id);
        if (ObjectUtil.isNull(obj) && b) {
            throw new RRException("申请不存在");
        }
        return obj;
    }

    @Override
    @Transactional
    public void assignedAccount(ApplyAreaAgentEntity areaAgent, SysUserForAreaAgentDTO userDTO) {
        //保存加盟商家管理员角色账号
        SysUserEntity user = new SysUserEntity();
        BeanUtils.copyProperties(userDTO, user);//将记录拷贝一份保存
        user.setIsAreaAgent(true);//区域代理管理员
        user.setIsShop(false);//商家管理员
        sysRoleService.saveUserRole(user, SysConstant.AREA_AGENT_ADMIN_ROLE);

        //保存商家与管理帐户的关系      //商家id//管理员id//主账号
        areaAgent.setAdminId(user.getUserId());
        this.baseMapper.updateById(areaAgent);
    }

    @Override
    public PageUtils queryCustomPage(Map<String, Object> params) {
        IPage<ApplyAreaAgentVo> page = this.baseMapper.queryCustomPage(new Query<ApplyAreaAgentVo>().getPage(params), params);

        Boolean loadOther = MapUtil.getBool(params, "load_other", false);
        if (loadOther) {
            page.getRecords().forEach(r -> {
                r.setShopNum(shopService.getShopNum(r.getAreaCode(), false));
                r.setOfflineShopNum(shopService.getShopNum(r.getAreaCode(), true));
            });
        }
        return new PageUtils(page);
    }

    @Override
    public SysUserEntity getAdminById(Long id) {
        ApplyAreaAgentEntity entity = this.loadById(id, true);
        return sysUserService.getById(entity.getAdminId());
    }

    @Override
    public List<ShopSlimVO> myOfflineShops(Long id) {
        ApplyAreaAgentEntity entity = this.loadById(id, true);
        return this.baseMapper.myOfflineShops(entity.getAreaCode());
    }

    @Override
    public List<ShopSlimVO> myOnlineShops(Long areaAgentId) {
        ApplyAreaAgentEntity entity = this.loadById(areaAgentId, true);
        return this.baseMapper.myOnlineShops(entity.getAreaCode());
    }

    @Override
    public void setAreaAgentParams(Long areaAgentId, Map<String, Object> params) {
        ApplyAreaAgentEntity one = this.lambdaQuery()
                .eq(ApplyAreaAgentEntity::getId, areaAgentId)
                .eq(ApplyAreaAgentEntity::getStatus, 1).one();
        if (ObjectUtil.isNotNull(one)) {
            params.put("province_code", one.getProvinceCode());
            params.put("city_code", one.getCityCode());
            params.put("area_code", one.getAreaCode());
        }
    }

    @Override
    public String getCodeByAreaAgentId(Long areaAgentId) {
        ApplyAreaAgentEntity entity = this.loadById(areaAgentId, false);
        if (ObjectUtil.isNotNull(entity)) {
            return accountService.getCodeById(entity.getUserId());
        }
        return null;
    }
}
